package com.szl.group.common.model;

import com.szl.group.common.enums.ResultCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import static com.szl.group.common.enums.ResultCodeEnum.OK;

/**
 * description:
 * author: shenxiaolong
 * date: 2020/6/20  16:57
 */
@ApiModel(value = "统一响应对象")
@Data
@Builder
@AllArgsConstructor
public class R {

    @ApiModelProperty(value = "响应码", example = "200")
    private int code;

    @ApiModelProperty(value = "请求message", example = "请求成功")
    private String message;

    @ApiModelProperty(value = "响应内容")
    private Object data;

    public R() {
        this.code = OK.getCode();
        this.message = OK.getMessage();
    }

    public R(int code) {
        this.code = code;
    }

    public R(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public R(Object data) {
        this.data = data;
        this.code = OK.getCode();
        this.message = OK.getMessage();
    }

    /**
     * 带result的实体
     *
     * @param result 结果数据
     * @return 返回包装实体
     */
    public static R success(Object result) {
        return success(result, 200);
    }

    /**
     * 不带result的实体
     *
     * @return 带code包装返回实体
     */
    public static R success() {
        return new R(200);
    }

    /**
     * custom response entity's status.
     *
     * @param result 结果集
     * @param code   响应返回码
     * @return
     */
    public static R success(Object result, int code) {
        return new R(code, "success", result);
    }

    /**
     * custom response entity's status.
     *
     * @param code    响应返回码
     * @param message
     * @return
     */
    public static R success(int code, String message) {
        return new R(code, message);
    }

    /**
     * not recommended this method.
     */
    public static R fail(String message) {
        return fail(500, message);
    }

    /**
     * use this method specifies status
     *
     * @param code    错误码
     * @param message 错误信息
     * @return 响应视图实体类
     */
    public static R fail(int code, String message) {
        return new R(code, message);
    }

    /**
     * use this method specifies status
     *
     * @param responseCodeEnum 异常枚举
     * @param message          错误信息
     * @return 响应视图实体类
     */
    public static R fail(ResultCodeEnum responseCodeEnum, String message) {
        return new R(responseCodeEnum.getCode(), message);
    }
}
